package com.hk.huakangcompany.controller;

import com.hk.huakangcompany.commons.security.CommonResult;
import com.hk.huakangcompany.model.vo.LoginAdmin;
import com.hk.huakangcompany.service.AdminService;
import com.hk.huakangcompany.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/8 10:00
 * @Statement: 测试跨域携带Cookie使用
 */
@RestController
@RequestMapping("/s")
public class SSController {

    @Value("${jwt.tokenHead}")
    String tokenHead;

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/test")
    public CommonResult test(@RequestBody LoginAdmin loginAdmin,HttpServletRequest request) {

//        存储Session
        /*String s = "admin123";
        session.setAttribute("s",s);*/
//        redis
        /*Admin admin = new Admin("sadasdas","121456");
        jedis.set("admin", JSON.toJSONString(admin));
        Result result = CommonResult.successResult(s);*/
        HashMap<String, String> data = new HashMap<>();
        String token = null;
        try {
            token = adminService.toLogin(loginAdmin,request);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("用户名或密码错误");
        }
        if (StringUtils.isEmpty(token)){
            return CommonResult.failed("用户名或密码错误");
        }
        data.put("tokenHead",tokenHead);
        data.put("access_token",token);
        // localStorage.setItem("Authorization","Bearer sdsdfdfds")
        // $ajax{data:{},type:"",header:{"Authorization":"Bearer sdsdfdfds"}}
        return CommonResult.success(data);
    }

    @PostMapping("/test1")
    public LoginAdmin test1(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        String token = header.substring(7);
//        获取负载
        Claims claims = jwtTokenUtil.getClaimsFromToken(token);
        String name = (String) claims.get("name");
        LoginAdmin loginAdmin = LoginAdmin.builder().name(name).build();
        return loginAdmin;
//        测试Session跨域后是否可以拿到
        /*String s = (String) session.getAttribute("s");
        System.out.println("s===="+s);*/
//        redis
        /*String admin = jedis.get("admin");
        Admin admin1 = JSON.parseObject(admin, Admin.class);
        System.out.println("admin=="+admin1);*/
//        return "success";
    }

}
